/**
 * 审批流列表
 */
import { useState, useEffect, useRef } from 'react';
import { Button, Space, Spin, List, Card, Input, message as m } from 'antd';
import { Modal } from 'com';
import menuStore from 'store/menu';
import { GetMyAuditFlow, UpdateMyFlow } from 'api/teacher_attendance_audit';
import { confirm } from '@/utils/common';
import dayjs from 'dayjs';

/**
 * 格式化字符串
 */
const formatString = 'YYYY-MM-DD HH:mm:ss';

/**
 * 处理课程时间
 * @param {*} param0 
 * @param {*} isFrom 
 * @returns 
 */
const handleCourseTime = ({ ffrom_date, fend_date, efrom_date, eend_date }, isFrom = true) => ffrom_date && `${dayjs(isFrom ? ffrom_date : efrom_date).format(formatString)} 至 ${dayjs(isFrom ? fend_date : eend_date).format(formatString)}`


export default props => {
    const { flow, onOK } = props;

    /**
     * 获取审批流的loading
     */
    const [flowLoading, setFlowLoading] = useState(false);
    /**
     * 审批loading
     */
    const [auditLoading, setAuditLoading] = useState(false);
    /**
     * 是否显示可输入文本框
     */
    const [showText, setShowText] = useState(false);
    /**
     * 输入的消息
     */
    const [message, setMessage] = useState('');
    /**
     * 审批流
     */
    const [flows, setFlows] = useState([]);
    /**
     * 审批modal
     */
    const modal = useRef();

    /**
     * 打开审批窗体
     * @param {*} row 
     */
    const open = async () => {
        try {
            modal.current.show();
            setFlowLoading(true);
            const list = await GetMyAuditFlow(flow.id);
            setFlows(list);
        } catch (error) { }
        setFlowLoading(false);
    }

    /**
     * 取消
     */
    const cancel = () => {
        modal.current.hide();
        setMessage('');
        setShowText(false);
    }

    /**
     * 提交
     */
    const ok = async status_id => {
        if (status_id === 36 && !message?.trim()) {
            return m.warning('消息不能为空');
        }
        try {
            await confirm(`您确定要【${status_id === 36 ? '提交' : '撤回'}】吗？`);
            setAuditLoading(true);
            await UpdateMyFlow({ status_id, id: flow.id, message });
            cancel();
            onOK();
        } catch (error) { }
        setAuditLoading(true);
    }

    useEffect(() => {
        flow?.id && open();
    }, [flow]);

    return <Modal bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }} title="更新考勤" ref={modal} footer={<Space>
        <Button onClick={cancel}>取消</Button>
        {
            showText ? <>
                <Button type="primary" onClick={() => setShowText(false)}>隐藏</Button>
                <Button type="primary" loading={auditLoading} onClick={() => ok(36)}>确定</Button>
            </> : <>
                {[36, 40].includes(flow?.status_id) && <Button type="primary" onClick={() => ok(41)}>撤回</Button>}
                {flow?.status_id === 40 && <Button type="primary" onClick={() => setShowText(true)}>重新提交</Button>}
            </>
        }
    </Space>}>
        <Spin spinning={flowLoading}>
            <List bordered dataSource={[
                `考勤类型：${flow.attendance_name}`,
                ...(flow.from_date ? [`时间：${dayjs(flow.from_date).format(formatString)} 至 ${dayjs(flow.end_date).format(formatString)}`] : [`我的课程：${handleCourseTime(flow)}`, `要调换的课程：${handleCourseTime(flow, false)}`]),
                `消息：${flow.message}`
            ]} renderItem={(item) => <List.Item>{item}</List.Item>}
            ></List>
            <List dataSource={flows} renderItem={({ id, step, status_name, audit_name, date, auditMessage, message, auditors }) => <List.Item style={{ padding: "10px 0" }} key={id}>
                <Card title={`第${step}步`} style={{ width: "100%" }}>
                    <div>状态：{status_name}</div>
                    {date && <>
                        <div>审批人：{audit_name}</div>
                        <div>审批日期：{dayjs(date).format(formatString)}</div>
                    </>}
                    {message && <div>我的消息：{message}</div>}
                    {date && <div>审批消息：{auditMessage}</div>}
                    {auditors && <div>下一步审批人：{auditors.map(c => c.teacher_name).join('，')}</div>}
                </Card>
            </List.Item>} />
            <div style={{ display: showText ? '' : 'none' }}>
                <h3>消息：</h3>
                <Input.TextArea value={message} onChange={e => setMessage(e.target.value)}></Input.TextArea>
            </div>
        </Spin>
    </Modal>
}